package com.example.servlet.bookServlet;



import com.example.dao.BookDao;
import com.example.entity.Book;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addbook")
public class BookAddServlet extends HttpServlet {
    private BookDao bookDao = new BookDao();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单数据
        String name = request.getParameter("name");
        String author = request.getParameter("author");
        String publisher = request.getParameter("publisher");
        String prices = request.getParameter("price");
        int price = Integer.parseInt(prices.trim());
        System.out.println("==============");
        System.out.println("添加信息：");
        System.out.println(name);
        System.out.println(author);
        System.out.println(publisher);
        System.out.println(prices);
        // 创建学生对象
        Book book = new Book(name,author,publisher,price);
        // 保存到数据库
        boolean b = bookDao.addBook(book);
        if (b) {
            System.out.println("添加成功!");
            response.getWriter().write("添加成功！");
            //请求转发
            request.getRequestDispatcher("index.jsp").forward(request, response);

        } else {
            System.out.println("添加失败!");
            response.getWriter().write("添加失败，请稍后重试！");
            response.sendRedirect("addbook.jsp");
        }

    }
}
